﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RFID_EX_WineSecurity.Dao {
    class DBHelper {
        private static readonly string SERVER = "localhost";
        private static readonly string SERVER_PORT = "3306";
        private static readonly string USER = "root";
        private static readonly string PASSWD = "root";
        private static readonly string DATABASE_NAME = "WineSecurity";
        
        private static readonly string MYSQL_CONN = "Server="+ SERVER + ";user id="+ USER + ";password="+ PASSWD + ";Database="+ DATABASE_NAME + ";Port="+ SERVER_PORT + ";charset=utf8;";
        private MySqlConnection connection;

        
        private void Connect() {
            connection = new MySqlConnection(MYSQL_CONN);
            connection.Open();
        }

        private void DisConnect() {
            if (connection != null) {
                connection.Close();
                connection = null;
            }
        }

        private static readonly string TABLE_NAME = "Tag";
        public bool QueryTag(string tagId) {
            if (connection == null) {
                Connect();
            }
            string sql = "SELECT * FROM "+ TABLE_NAME + " WHERE tagId='"+tagId+"'";
            Console.WriteLine(sql);
            MySqlCommand command = new MySqlCommand(sql, connection);

            MySqlDataReader result = command.ExecuteReader();
            int rNum = 0;
            while (result.Read()) {
                rNum++;
            }
            Console.WriteLine("rNum=" + rNum);
            DisConnect();
            result.Close();
            return rNum > 0 ? true : false;
        }

        public bool AddTag(string tagId) {
            if (connection == null) {
                Connect();
            }
            string sql = "INSERT INTO "+ TABLE_NAME +"(tagId) values('"+ tagId + "')";
            MySqlCommand command = new MySqlCommand(sql, connection);
            int r = command.ExecuteNonQuery();
            DisConnect();
            if (r > 0) {
                return true;
            }
            return false;
        }

    }
}
